// featurePackage/pages/orderDetail/orderDetail.js
import {
  queryOrderDetail,
  cancelOrder,
  delOrder,
  orderPay,
  confirmOrderReceive
} from "../../../service/jb_order_service"
import {
  SERVICE_URL,
  SERVICE_ID,
} from "../../../service/base_service"
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    menuTop: app.globalData.menuButton.top,
    menuHeight: app.globalData.menuButton.height,
    orderStatus: 0,
    addressInfo: {
      name: "",
      phone: "",
      address: ""
    },
    orderId: null,
    orderInfo: {
      systemStore: {},
      pstatus: {}
    }, //订单详情
    orderSteps: [
      {
        text: "待付款",
        desc: ""
      },
      {
        text: "待发货",
        desc: ""
      },
      {
        text: "待收货",
        desc: ""
      },
      {
        text: "待评价",
        desc: ""
      },
      {
        text: "已完成",
        desc: ""
      }
    ],
    orderActive: 0,
    orderTopRemark: "",//订单顶部提示语

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.orderId) {
      this.setData({
        orderId: options.orderId
      })
    }

  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.queryOrderDetail();
  },
  queryOrderDetail() {
    // let res = {
    //   "code": 200,
    //   "message": "操作成功",
    //   "data": {
    //     "id": 28,
    //     "orderId": "order33014170532844924694119",
    //     "realName": "蒋俊",
    //     "userPhone": "14632754653",
    //     "userAddress": "四川省成都市锦江区房间号都开始浪费科技大厦理发好受打击看哈",
    //     "freightPrice": "0.00",
    //     "totalPrice": "0.10",
    //     "proTotalPrice": "0.10",
    //     "payPrice": "0.10",
    //     "payPostage": "0.00",
    //     "deductionPrice": "0.00",
    //     "couponId": 0,
    //     "couponPrice": "0.00",
    //     "paid": true,
    //     "payTime": "2024-01-15 22:21:08",
    //     "payType": "weixin",
    //     "createTime": "2024-01-15 22:20:49",
    //     "status": 2,
    //     "refundStatus": 0,
    //     "refundReasonWapImg": null,
    //     "refundReasonWapExplain": null,
    //     "refundReasonTime": null,
    //     "refundReasonWap": null,
    //     "refundReason": null,
    //     "refundPrice": "0.00",
    //     "deliveryName": "顺丰",
    //     "deliveryType": "express",
    //     "deliveryId": 'SF1232143434343',
    //     "useIntegral": 0,
    //     "mark": "",
    //     "isMerCheck": 0,
    //     "combinationId": 0,
    //     "pinkId": 0,
    //     "seckillId": 0,
    //     "bargainId": 0,
    //     "verifyCode": "",
    //     "storeId": 0,
    //     "shippingType": 1,
    //     "isChannel": 1,
    //     "type": 0,
    //     "payTypeStr": "微信支付",
    //     "orderStatusMsg": "已收货,快去评价一下吧",
    //     "systemStore": null,
    //     "statusPic": null,
    //     "orderInfoList": [
    //       {
    //         "attrId": 20,
    //         "productId": 9,
    //         "cartNum": 1,
    //         "image": "images/product/2023-12-30/1703949611412/555555.webp",
    //         "storeName": "测试商品",
    //         "price": "0.10",
    //         "isReply": 0,
    //         "sku": "默认"
    //       }
    //     ]
    //   }
    // }
    // this.setData({
    //   orderInfo: res.data,
    //   orderActive: res.data.status + 1,
    // })
    // if (!res.data.paid) {
    //   //订单未支付
    //   this.setData({
    //     orderTopRemark: res.data.orderStatusMsg
    //   })
    // }
    // this.dealOrderShow();
    // return;


    wx.showLoading();
    queryOrderDetail(this.data.orderId).then(res => {
      console.log(res)
      wx.hideLoading()
      if (res.code == 200) {
        this.setData({
          orderInfo: res.data,
          orderActive: res.data.status + 1,
          orderTopRemark: res.data.orderStatusMsg || "",
        })
        if (!res.data.paid) {
          //订单未支付
          this.setData({
            orderActive: 0,
          })
        }
        this.dealOrderShow();
      }

    }).catch(err => {
      wx.hideLoading()
      console.error("JJLog:queryOrderDetail", err)
      wx.showToast({
        title: err || '查询失败',
        icon: "none"
      })

      setTimeout(() => {
        wx.navigateBack()
      }, 2000)
    })
  },
  dealOrderShow() {
    //1.地址展示
    let addressInfo = {
      name: this.data.orderInfo.realName,
      phone: this.data.orderInfo.userPhone,
      address: this.data.orderInfo.userAddress
    }
    this.setData({
      addressInfo: addressInfo
    })
  },

  //取消订单:
  cancelOrderAction() {
    wx.navigateBack({
      delta: 0,
    })
    return;
    wx.showModal({
      title: '提示',
      content: '确认取消当前订单?',
      confirmColor: "#ff0000",
      success: res => {
        if (res.confirm) {
          wx.showLoading();
          cancelOrder({ id: this.data.orderInfo.id }).then(res => {
            wx.hideLoading();
            if (res.code == 200) {
              wx.showToast({
                title: '取消成功',
                icon: "none"
              })
              setTimeout(() => {
                wx.navigateBack({
                  delta: 1
                })
              }, 2000)
            }
          }).catch(err => {
            wx.hideLoading();
            wx.showToast({
              title: err || "取消失败",
              icon: "none"
            })
            console.error("JJLog:cancelOneOrder", err);
          })
        }
      }
    })
  },

  //删除订单:
  deleteOrder() {
    wx.showModal({
      title: '提示',
      content: '确认删除当前订单?',
      success: res => {
        if (res.confirm) {
          wx.showLoading();
          delOrder({ id: this.data.orderInfo.id }).then(res => {
            wx.hideLoading();
            if (res.code == 200) {
              wx.showToast({
                title: '删除成功',
                icon: "none"
              })
              setTimeout(() => {
                wx.navigateBack({
                  delta: 1
                })
              }, 2000)
            }
          }).catch(err => {
            wx.hideLoading();
            wx.showToast({
              title: err || "删除失败",
              icon: "none"
            })
            console.error("JJLog:delOrder", err);
          })
        }
      }
    })
  },

  // 立即支付
  payAgain() {


    let requestData = {
      orderNo: this.data.orderInfo.porderId,
      payChannel: "weixinh5",
      payType: "weixin",
      scene: 0
    }

    wx.showLoading({
      title: '支付中...',
    })

    orderPay(requestData).then(res => {
      console.log("JJLog:支付回调:" + JSON.stringify(res));
      if (res.code == 200) {

        console.log("JJLog:这里没来")
        let payData = res.data.jsConfig;
        wx.requestPayment({
          timeStamp: payData.timeStamp,
          nonceStr: payData.nonceStr,
          package: payData.packages,
          signType: 'MD5',
          paySign: payData.paySign,
          success: (res) => {
            wx.hideLoading();
            console.log("JJLog:微信支付成功回调:" + JSON.stringify(res));
            wx.showToast({
              title: '支付成功',
              icon: "success",
              duration: 2000
            })
            this.queryOrderDetail();

          },
          fail: (err) => {
            wx.hideLoading();
            wx.showToast({
              title: '支付失败',
              icon: "none"
            })
            console.log("JJLog:微信支付失败回调:" + JSON.stringify(err));
          }
        });
      }
    }).catch(err => {
      console.error("JJLog购买商品失败:" + JSON.stringify(err));
      wx.hideLoading();
      wx.showToast({
        title: err || "支付失败",
        icon: "none"
      })
    })
  },
  //确认收货点击
  sureTakeGoodAction() {
    wx.showModal({
      title: '提示',
      content: '确认当前订单已收到?',
      success: res => {
        if (res.confirm) {
          wx.showLoading();
          confirmOrderReceive(this.data.orderInfo.id).then(res => {
            // console.log("JJLog:我的订单列表===:" + JSON.stringify(res));
            wx.hideLoading();
            if (res.code == 200) {
              wx.navigateTo({
                url: '/featurePackage/pages/commonSuccess/commonSuccess?type=3',
              })
            }
          }).catch(err => {
            wx.hideLoading();
            wx.showToast({
              title: err || "收货失败",
              icon: "none"
            })
            console.error("JJLog:confirmOrderReceive", err);
          })
        }
      }
    })
  },

  //申请退款按钮点击
  applyReturnAction() {
    wx.navigateTo({
      url: '/featurePackage/pages/order/applyReturnGood/applyReturnGood?orderId=' + this.data.orderInfo.orderId,
    })
  },
  //查看物流信息点击
  seeExpressAction() {
    wx.navigateTo({
      url: '/featurePackage/pages/order/orderDeliverInfo/orderDeliverInfo?orderNo=' + this.data.orderInfo.orderId,
    })
  },
  // 复制订单号方法
  copyOrderIdAction() {
    let text = this.data.orderInfo.orderId
    wx.setClipboardData({
      data: text,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              title: '复制订单号成功'
            })
          },
          fail: function (err) {
            wx.showToast({
              title: '复制失败',
              icon: "none"
            })
          }
        })
      }
    })
  },
    //拨打电话
    makePhoneAction(e){
      let phone = e.currentTarget.dataset.phone;
      wx.makePhoneCall({
        phoneNumber: phone,
        fail:err=>{
 
        }
      })
   },
  openServiceAction() {
    wx.openCustomerServiceChat({
      extInfo: { url: SERVICE_URL },
      corpId: SERVICE_ID,
      success(res) { },
      fail(err) {
        console.log('调用失败:', err);
      }
    })
  },

})